package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.articleDto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmArticleAutoReview;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shitou
 * @className WmArticleAutoReviewImpl
 * @description: 文章自动审核实现类
 */
@Service
@Slf4j
@Transactional
public class WmArticleAutoReviewImpl implements WmArticleAutoReview {

    @Resource
    private WmNewsMapper wmNewsMapper;

    @Resource
    private IArticleClient iArticleClient;

    /**
     * 文章自动审核
     *
     * @param newsId
     * @return
     */
    @Async
    @Override
    public void autoScanWmNews(Integer newsId)  {
        log.info("文章自动审核");
        if (newsId < 0) {
            throw new RuntimeException("无效参数");
        }
        // 先查询文章是否存在
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            throw new RuntimeException("文章不存在");
        }

        // 抽取文章内容和图片
        HashMap<String, Object> contentAndImgMap = extractContentAndImg(wmNews);

        // 自管理的敏感词过滤
        boolean isSensitive = handleSensitiveScan(contentAndImgMap.get("text").toString(), wmNews);
        if (!isSensitive) return;

        boolean flag = true;

        // 1 为提交状态，进行审核
        if (wmNews.getStatus() == 1) {
            // 审核文章内容标题和内容`
            flag = ReviewTitleAndContent(wmNews, contentAndImgMap.get("text"));
        }

        if (!flag) {
            return;
        }

        // 审核图片
        flag = ReviewImages(wmNews, (List<String>) contentAndImgMap.get("image"));
        if (!flag) {
            return;
        }

        //  审核成功，保存app端的相关的文章数据
        ResponseResult responseResult = saveArticle(wmNews);
        if (!responseResult.getCode().equals(200)) {
            throw new RuntimeException("保存app端相关文章数据失败");
        }
        wmNews.setArticleId((Long) responseResult.getData());
        updateNews(wmNews, "审核成功", 9);

    }

    @Resource
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词过滤
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        // 获取全部的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateNews(wmNews, "当前文章中存在违规内容" + map, 2);
            flag = false;
        }
        return flag;
    }

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmUserService wmUserService;

    /**
     * 保存文章
     *
     * @param wmNews
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
        // 补充属性
        // 布局
        articleDto.setLayout(wmNews.getType());
        // 频道
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelName(wmChannel.getName());
        }
        // 作者id
        articleDto.setAuthorId(wmNews.getUserId());
        // 作者名字
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorName(wmUser.getName());
        }
        // 设置文章id
        Long articleId = wmNews.getArticleId();
        log.info("保存文章--文章id{}", articleId);
        if (articleId != null && articleId > 0) {
            articleDto.setId(articleId);
        }
        articleDto.setCreatedTime(new Date());


        return iArticleClient.saveArticle(articleDto);

    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片
     *
     * @param wmNews
     * @param images
     * @return
     */
    private boolean ReviewImages(WmNews wmNews, List<String> images) {
        boolean flag = true;

        if (images.size() == 0) {
            return flag;
        }

        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        // minIo下载图片
        List<byte[]> imgList = new ArrayList<>();
        try {
            for (String img : images) {
                byte[] bytes = fileStorageService.downLoadFile(img);

                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);

                //审核是否包含自管理的敏感词
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if (!isSensitive) {
                    return isSensitive;
                }

                //图片识别文字审核---end-----

                imgList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 调用图片审核接口
        try {
            Map mapScan = greenImageScan.imageScan(imgList);
            if (mapScan != null) {
                // 审核失败
                if (mapScan.get("suggestion").equals("block")) {
                    updateNews(wmNews, "图片违规", 2);
                    flag = false;
                }
                // 审核不确定 走人工审核
                if (mapScan.get("suggestion").equals("review")) {
                    updateNews(wmNews, "图片不确定", 3);
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核文章内容标题和内容 方法
     *
     * @param wmNews
     * @return
     */
    private boolean ReviewTitleAndContent(WmNews wmNews, Object content) {
        String title = wmNews.getTitle();
        // 标题和文章不能为空
        if ("".equals(content) || "".equals(title)) {
            throw new RuntimeException("标题和文章不能为空");
        }
        boolean flag = true;
        // 文章标题审核
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle());
            if (map != null) {
                // 审核失败
                log.info("map.get:{}", map.get("suggestion"));
                if (map.get("suggestion").equals("block")) {
                    updateNews(wmNews, "标题违规", 2);
                    log.info("标题违规");
                    flag = false;
                }
                // 审核不确定 走人工审核
                if (map.get("suggestion").equals("review")) {
                    updateNews(wmNews, "标题不确定", 3);
                    log.info("标题不确定");
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        // 文章内容审核
        try {
            Map map = greenTextScan.greeTextScan(content.toString());
            if (map != null) {
                // 审核失败
                if (map.get("suggestion").equals("block")) {
                    updateNews(wmNews, "文章内容违规", 2);
                    log.info("文章内容违规");
                    flag = false;
                }
                // 审核不确定 走人工审核
                if (map.get("suggestion").equals("review")) {
                    updateNews(wmNews, "文章内容不确定", 3);
                    log.info("文章内容不确定");
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 抽取文章内容和图片
     *
     * @param wmNews
     * @return
     */
    private HashMap<String, Object> extractContentAndImg(WmNews wmNews) {
        // [{"type":"image","value":"http://192.168.113.130:9000/news/2022/06/14/fd391400c722484fb22ad54b98c2937f.jpg"}]

        // 内容和图片容器
        HashMap<String, Object> contentAndImgMap = new HashMap<>();
        StringBuilder contentString = new StringBuilder();
        List<String> imageList = new ArrayList<>();

        if (StringUtils.isNotEmpty(wmNews.getContent())) {
            // JSON 转 map
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                // 类型为text 存入 ContentList
                if (map.get("type").equals("text")) {
                    contentString.append(((String) map.get("value")));
                }
                // 类型为 image 存入
                if (map.get("type").equals("image")) {
                    imageList.add((String) map.get("value"));
                }
            }
        }
        // 提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(split));
        }

        contentAndImgMap.put("text", contentString);
        contentAndImgMap.put("image", imageList);
        return contentAndImgMap;
    }

    // 修改文章
    private void updateNews(WmNews wmNews, String reason, Integer status) {
        // 原因
        wmNews.setReason(reason);
        // 状态
        wmNews.setStatus(status);
        wmNewsMapper.updateById(wmNews);
    }

}
